#include <errno.h>
#include <stdio.h>
#include <string.h>

static void get_file_var(char *var, const char *filename, int max_len)
{
  int i, c;
  const char *p;
  
  p = strrchr(filename, '/');
  if (p == NULL)
    p = filename;

  for (i = 0; i+1 < max_len && p[i] != '\0'; i++) {
    c = p[i];
    if ((c >= 'A' && c <= 'Z')
	|| (c >= 'a' && c <= 'z')
	|| (c >= '0' && c <= '9'))
      var[i] = c;
    else
      var[i] = '_';
  }
  var[i] = '\0';
}

static int file2c(const char *progname, const char *out_file, const char *in_file)
{
  FILE *in, *out;
  char var_name[32];
  int c, n;

  in = fopen(in_file, "r");
  if (! in) {
    printf("%s: can't open '%s': %s\n", progname, in_file, strerror(errno));
    return 1;
  }
  out = fopen(out_file, "w");
  if (! out) {
    fclose(in);
    printf("%s: can't open '%s': %s\n", progname, out_file, strerror(errno));
    return 1;
  }

  get_file_var(var_name, in_file, sizeof(var_name));
  fprintf(out, "/* Auto-generated by file2c, do not edit! */\n");
  fprintf(out, "const static unsigned char %s[] = {", var_name);
  n = 0;
  while ((c = getc(in)) != EOF) {
    if (n++ % 12 == 0)
      fprintf(out, "\n ");
    fprintf(out, " 0x%02x,", (unsigned int) c);
  }
  fprintf(out, "\n};\n");
  fclose(out);
  fclose(in);
  return 0;
}

int main(int argc, char *argv[])
{
  if (argc != 3) {
    printf("USAGE: %s output.c input_file\n", argv[0]);
    return 1;
  }
  return file2c(argv[0], argv[1], argv[2]);
}
